import fs from "fs-extra";
import {globalConfig} from "../config";
import {UNKNOWN_PROJECT_OPTIONS} from "../constant";
import {ProjectTypeOptions} from "../types";

/**
 * 项目分类
 */
export class ProjectClass {

  /**
   * 检测项目类型
   * @param dirPath 目录路径
   * @returns 项目类型
   */
  public static async detectProjectType(dirPath: string): Promise<ProjectTypeOptions> {
    try {
      const files = await fs.readdir(dirPath);

      const projectTypes = globalConfig.config.scan.projectTypes

      for (let type in projectTypes) {
        const mainFiles = projectTypes[type].mains;

        // 检查是否有任何匹配的主文件
        const matches = mainFiles.some(filePattern => {
          // 检查是否为完全匹配的文件名
          if (files.includes(filePattern)) {
            return true;
          }

          // 处理以.开头的扩展名模式 (如 .csproj, .sln)
          if (filePattern.startsWith('.')) {
            return files.some(file => file.endsWith(filePattern));
          }

          return false;
        });

        if (matches) {
          return Object.assign(projectTypes[type], {
            type: type
          });
        }
      }

      return UNKNOWN_PROJECT_OPTIONS;
    } catch (error) {
      return UNKNOWN_PROJECT_OPTIONS;
    }
  }
}
